<template>
  <div class="wechat-mnp-config">
    <div class="card-wrap mb10 animate-on-enter">
      <a-space wrap>
        <a-button :icon="h(ReloadOutlined)" @click="onRefresh" :loading="loading">
          刷新
        </a-button>
      </a-space>
    </div>

    <div class="card-wrap mb10 animate-on-enter animate-delay-1">
      <a-alert :message="formState.description" type="info" show-icon />
    </div>

    <div class="card-wrap animate-on-enter animate-delay-2">
      <a-spin :spinning="loading">
        <a-form ref="formRef" :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }" :rules="rules"
          @finish="onSubmit">
          <a-form-item label="AppID" :name="['value', 'app_id']">
            <a-input v-model:value="formState.value.app_id" placeholder="请输入微信小程序AppID" />
          </a-form-item>

          <a-form-item label="AppSecret" :name="['value', 'secret']">
            <a-input v-model:value="formState.value.secret" placeholder="请输入微信小程序AppSecret" />
          </a-form-item>

          <a-form-item label="Token" :name="['value', 'token']">
            <a-input v-model:value="formState.value.token" placeholder="请输入消息推送Token" />
          </a-form-item>

          <a-form-item label="EncodingAESKey" :name="['value', 'aes_key']">
            <a-input v-model:value="formState.value.aes_key" placeholder="请输入消息加解密密钥" />
          </a-form-item>

          <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
            <a-button type="primary" :icon="h(SaveOutlined)" html-type="submit" :loading="saveLoading">
              保存配置
            </a-button>
          </a-form-item>
        </a-form>
      </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import { SaveOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { baseAPI } from '@/api/api.js'

// 响应式数据
const formRef = ref()
const loading = ref(false)
const saveLoading = ref(false)

// 表单数据
const formState = reactive({
  id: '',
  name: '微信小程序配置',
  key: 'wechat_mnp_config',
  value: {
    app_id: '',
    secret: '',
    token: '',
    aes_key: ''
  },
  description: '微信小程序基础配置信息'
})

// 表单验证规则
const rules = {
  value: {
    app_id: [
      { required: true, message: '请输入微信小程序AppID', trigger: 'change' },
    ],
    secret: [
      { required: true, message: '请输入微信小程序AppSecret', trigger: 'change' }
    ],
    token: [
      { required: true, message: '请输入消息推送Token', trigger: 'change' }
    ],
    aes_key: [
      { required: true, message: '请输入消息加解密密钥', trigger: 'change' }
    ]
  }
}

// 方法
function loadConfig() {
  loading.value = true
  return baseAPI.get('PlatformConfig/getPlatformConfig', {
    key: 'wechat_mnp'
  })
    .then(function (response) {
      if (response.code === 200 && response.result) {
        // 如果有配置数据，则填充表单
        const config = response.result

        // 处理value，确保它是一个对象
        let configValue = config.value || {}
        if (typeof configValue === 'string') {
          try {
            configValue = JSON.parse(configValue)
          } catch (e) {
            console.error('解析value失败:', e)
            configValue = {}
          }
        }

        Object.assign(formState, {
          id: config.id || '',
          name: config.name || '微信小程序配置',
          key: config.key || 'wechat_mnp_config',
          value: {
            app_id: configValue.app_id || '',
            secret: configValue.secret || '',
            token: configValue.token || '',
            aes_key: configValue.aes_key || ''
          },
          description: config.description || '微信小程序基础配置信息'
        })
      }
    })
    .catch(function (error) {
      console.error('加载配置失败:', error)
      message.error('加载配置失败')
    })
    .finally(function () {
      loading.value = false
    })
}

function onSubmit(values) {
  saveLoading.value = true

  const submitData = {
    name: formState.name,
    key: formState.key,
    value: values.value
  }


  return baseAPI.post('PlatformConfig/saveConfig', submitData)
    .then(function (response) {
      if (response.code === 200) {
        message.success('保存成功')
        // 重新加载配置
        return loadConfig()
      } else {
        message.error(response.message || '保存失败')
      }
    })
    .catch(function (error) {
      console.error('保存失败:', error)
      message.error('保存失败')
    })
    .finally(function () {
      saveLoading.value = false
    })
}


const onRefresh = () => {
  loadConfig()
}

// 生命周期
onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.wechat-mnp-config {
  .card-wrap {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    h3 {
      margin-bottom: 16px;
      color: #333;
      font-weight: 600;
    }
  }

  .mb10 {
    margin-bottom: 16px;
  }

  .mt10 {
    margin-top: 16px;
  }

  .animate-on-enter {
    animation: fadeInUp 0.6s ease-out;
  }

  .animate-delay-1 {
    animation-delay: 0.1s;
  }

  .animate-delay-2 {
    animation-delay: 0.2s;
  }

  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }

    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
}
</style>